#!/usr/bin/env python3
# set coding: utf-8
"""
@Project : litewaf2
@File :    test.py
@Time :    2023/3/5 16:05
@Author :  richard zhu
@Email :   gaotao.zhugt@dtzhejiang.com
@purpose : 
"""

import json
from jsonschema import validate, SchemaError, ValidationError, FormatChecker,Draft202012Validator

# 编写schema：
my_schema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "TestInfo",
    "description": "some information about test",
    "type": "object",
    "properties": {
        "name": {
            "description": "Name of the test",
            "type": "string"
        },
        "age": {
            "description": "age of test",
            "type": "integer"
        },
        "rule": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["a", "b"],
                "properties": {
                    "a": {
                        "description": "a1",
                        "type": "string"
                    },
                    "b": {
                        "description": "b1",
                        "type": "integer"
                    }
                }
            }
        }
    },
    "required": [
        "name", "age", "rule"
    ]
}

rule_matchs = [
    {
        "match_args": [
            {
                "key": "http_args",
                "value": "src_ip"
            }
        ],
        "args_prepocess": [
            "none"
        ],
        "match_operator": "ipmask",
        "match_value": "127.0.0.2/24"
    }
]

rule_matchs_schema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "rule_matchs",
    "type": "array",
    "items": {
        "type": "object",
        "required": ["match_args", "args_prepocess", "match_operator", "match_value"],
        "properties": {
            "match_args": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["key", "value"],
                    "properties": {
                        "key": {
                            "type": "string"
                        },
                        "value": {
                            "type": "string"
                        }
                    },
                },
            },
            "args_prepocess": {
                "type": "array",
                "items": {
                    "type": "string"
                }
            },
            "match_operator": {
                "type": "string"
            },
            "match_value": {
                "type": "string"
            }
        },
    }
}

# json数据：
json_data = {
    "name": "python",
    "age": 25,
    "rule": [{
        "a": "124",
        "b": 123
    }]
}

# 验证：
# ret = validate(instance=json_data, schema=my_schema)

validate(instance=rule_matchs, schema=rule_matchs_schema, format_checker=Draft202012Validator.FORMAT_CHECKER)

factor_keys = {
    "factor_keys": [
        {
            "key": "http_args",
            "value": "host"
        },
        {
            "key": "http_args",
            "value": "src_ip"
        }
    ],
    "factor_match": [
        {
            "host": "ip.gaotao.club",
            "src_ip": "127.0.0.1",
            "action_value": {
                "rate": "2",
                "burst": "1"
            }
        }
    ]
}

factor_keys_schema = {
    "title": "rule_matchs",
    "type": "object",
    "required": ["factor_keys", "factor_match"],
    "properties": {
        "factor_keys":{
            "type": "array",
            "items": {
                "type": "object",
                "required": ["key", "value"],
                "properties": {
                    "key": {
                        "type": "string"
                    },
                    "value": {
                        "type": "string"
                    }
                }
            }
        },
        "factor_match": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["action_value"],
                "properties": {
                    "action_value": {
                        "type": "object",
                        "required":["rate", "burst"],
                        "properties": {
                            "rate": {
                                "type": "string"
                            },
                            "burst": {
                                "type": "string"
                            }
                        }
                    }

                }
            }
        }
    }
}

validate(instance=factor_keys, schema=factor_keys_schema)

# try:
#     validate(instance=json_data, schema=factor_keys_schema)
# except SchemaError as e:
#     print("验证模式schema出错：\n出错位置：{}\n提示信息：{}".format(" --> ".join([i for i in e.path]), e.message))
# except ValidationError as e:
#     print("json数据不符合schema规定：\n出错字段：{}\n提示信息：{}".format(" --> ".join([i for i in e.path]), e.message))
# else:
#     print("验证成功！")

from api.models import *
domain_dict = {}
rules_data = {}

for dom in WafDomain.objects.filter(status=True).filter(user_id_id='82573c454115'):
    rule_dict = {}
    waf_rules = WafRule.objects.filter(status=True).order_by('order')
    flow_rules = FlowRule.objects.filter(status=True).order_by('order')

    rgs = dom.rulegroup.filter(status=True)

    domain_with_port = "%s:%s" % (dom.domain, dom.port)
    domain_dict[domain_with_port] = {"rules": rule_dict}

    for rg in rgs:
        waf_rules = rg.waf_rule.filter(status=True).order_by('order')
        for _rule in waf_rules:
            if rule_dict.get(_rule.rule_type):
                rule_dict[_rule.rule_type].append(_rule.uuid)
            else:
                rule_dict[_rule.rule_type] = [_rule.uuid]

            if rules_data.get(_rule.rule_type):
                rules_data[_rule.rule_type].update({_rule.uuid: _rule.to_dict()})
            else:
                rules_data[_rule.rule_type] = {_rule.uuid: _rule.to_dict()}

        flow_rules = rg.flow_rule.filter(status=True).order_by('order')

        for _rule in flow_rules:
            if rule_dict.get(_rule.rule_type):
                rule_dict[_rule.rule_type].append(_rule.uuid)
            else:
                rule_dict[_rule.rule_type] = [_rule.uuid]
            if rules_data.get(_rule.rule_type):
                rules_data[_rule.rule_type].update({_rule.uuid: _rule.to_dict()})
            else:
                rules_data[_rule.rule_type] = {_rule.uuid: _rule.to_dict()}

print(domain_dict)
print(rules_data)